package com.egdigital.allzic.data.json;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.egdigital.allzic.data.object.Updater;

public class JsonParserUpdate {

	private static final String		TAG					= JsonParserUpdate.class.getSimpleName();	// log
	private static final String		TAG_ID				= "notice_id";
	private static final String		TAG_VERSION			= "notice_version";
	private static final String		TAG_TITLE			= "notice_title";
	private static final String		TAG_TEXT			= "notice_text";
	//
	private RequestQueue			mRequestQueue;
	private static JsonParserUpdate	mJsonParser;
	private JsonCallBack			mJsonCallback;
	private JSONArray				mJsonArrayUpdater	= null;
	private Updater					mUpdater;

	private JsonParserUpdate() {
		super();
		initAndStartRequestQueue();
	}

	public static JsonParserUpdate getInstance() {
		if (mJsonParser == null) {
			return new JsonParserUpdate();
		} else {
			return mJsonParser;
		}
	}

	public void initAndStartRequestQueue() {
		mRequestQueue = VolleyManager.getRequestQueue();
		mRequestQueue.start();
	}

	public void stopRequestQueue() {
		mRequestQueue.stop();
	}

	public void extractJsonObjectData(String url) {
		JsonArrayRequest request = new JsonArrayRequest(url, createMyReqSuccessListener(), createMyReqErrorListener());
		request.setTag(this);
		mRequestQueue.add(request);
		mJsonCallback.downloadStarted();
	}

	public void setJsonCallBack(JsonCallBack callback) {
		mJsonCallback = callback;
	}

	protected Response.Listener<JSONArray> createMyReqSuccessListener() {
		return new Response.Listener<JSONArray>() {

			public void onResponse(JSONArray jsonArray) {
				List<Updater> list = new ArrayList<Updater>();
				try {
					mJsonArrayUpdater = jsonArray;
					for (int i = 0; i < mJsonArrayUpdater.length(); i++) {
						JSONObject jsonObject = mJsonArrayUpdater.getJSONObject(i);
						mUpdater = new Updater(jsonObject.getString(TAG_ID), jsonObject.getString(TAG_VERSION), jsonObject.getString(TAG_TITLE), jsonObject.getString(TAG_TEXT));
						list.add(mUpdater);
					}
				} catch (Exception ex) {
				}
				mJsonCallback.downloadCompleted(list);
			}
		};
	}

	protected Response.ErrorListener createMyReqErrorListener() {
		return new Response.ErrorListener() {

			public void onErrorResponse(VolleyError error) {
				mJsonCallback.downloadEndedWithError(error);
			}
		};
	}
}